from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from routes.jzyx_api import app as jzyx_api_app
from routes.multi_routes import app as multi_routes_app
from routes.file_api import app as file_api_app
from routes.taskTimeExecutor import start_task_executor
import os
import sys

def get_base_path():
    """获取应用的基础路径，支持开发和打包环境"""
    if getattr(sys, 'frozen', False):
        # PyInstaller打包环境
        return sys._MEIPASS
    else:
        # 开发环境
        return os.path.dirname(os.path.abspath(__file__))

app = FastAPI()
# 添加 CORS 中间件
origins = [
    "http://localhost:63342",
    "http://10.8.50.48:63342",# 允许的前端应用源
    "http://10.8.50.48:8000",    # 其他服务的源（如果有）
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 可以根据需要设置允许的源
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有HTTP方法
    allow_headers=["*"],  # 允许所有HTTP头
)

# 添加主页路由
@app.get("/")
async def read_main():
    """提供主页HTML文件"""
    base_path = get_base_path()
    html_file_path = os.path.join(base_path, "main.html")
    
    if os.path.exists(html_file_path):
        return FileResponse(html_file_path)
    else:
        # 尝试备用路径
        alternative_paths = [
            os.path.join(os.getcwd(), "main.html"),
            os.path.join(os.path.dirname(sys.executable), "main.html") if getattr(sys, 'frozen', False) else None,
            "main.html"
        ]
        
        for alt_path in alternative_paths:
            if alt_path and os.path.exists(alt_path):
                return FileResponse(alt_path)
        
        return {"message": f"主页文件未找到。基础路径: {base_path}, 尝试的路径: {html_file_path}"}

# 将不同的 API 挂载到不同的路径下
app.mount("/jzyx", jzyx_api_app)
app.mount("/test", multi_routes_app)
app.mount("/api/", file_api_app)

# 启动定时任务执行器
start_task_executor()

if __name__ == "__main__":
    import uvicorn
    import os
    
    # 设置MySQL连接器环境变量以解决本地化问题
    os.environ['MYSQL_PWD'] = ''
    os.environ['LC_ALL'] = 'C'
    os.environ['LANG'] = 'C'
    
    # 检查是否是打包后的可执行文件环境
    is_packaged = getattr(sys, 'frozen', False)
    
    if is_packaged:
        # 打包环境：禁用reload，使用较少的日志
        uvicorn.run(app, host="0.0.0.0", port=8080, reload=False, log_level="info")
    else:
        # 开发环境：启用reload
        uvicorn.run(app, host="0.0.0.0", port=8080, reload=True)